<?php

namespace app\admin\controller;

use think\Controller;
use app\admin\model\User;
use think\facade\Session;
use think\facade\Url;

class Login extends Controller{

    /**
     * 后台登录
     * @return \think\Response
     */
    public function index(){
        $user = new User();
        //是否已经登录
        if ($user->isLogin()){
            $this->redirect('index/index');
        }
        if ($this->request->isAjax()){
            //获取数据
            $data = $this->request->post();
            //验证
            $result = $this->validate($data,'app\admin\validate\User.login');
            if ($result !== true){
                $this->error($result);
            }
            //判断登录
            if (true == $user->login($data['username'],$data['password'])){
                $this->success('登录成功',Url::build('index/index'));
            }
            $this->error('用户名或密码错误');
        }
        return $this->fetch();
    }

    /**
     * 退出登陆
     * @return mixed
     */
    public function logout(){
        (new User())->logout();
        $this->redirect('login/index');
    }


}
